package com.hcy.controller.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcy.common.Impl.CommonInfoBzImpl;
import com.hcy.common.dto.request.DirectionRequestDTO;
import com.hcy.common.dto.request.FindLocationRequestDTO;
import com.hcy.common.dto.request.TrackInfoRequestDTO;
import com.hcy.common.dto.response.GaoDeGfidsResponseDTO;
import com.hcy.common.dto.response.TrackInfoResponseDTO;
import com.hcy.common.entity.GaodeGfids;
import com.hcy.rabbitbasicmodel.enums.Code;
import com.hcy.rabbitbasicmodel.model.ResponseData;
import com.hcy.rabbitbasicutils.utils.MyHttpUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author huchenying
 * @Description 公共位置服务信息
 * @Date 2021/12/14 12:02
 */
@RestController
@RequestMapping("/location")
public class LocationInfoController {

    private static final Logger logger = LoggerFactory.getLogger(LocationInfoController.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MyHttpUtils myHttpUtils;
    @Value("${gaode_config.key}")
    private String key;
    @Value("${gaode_config.sid}")
    private String sid;
    @Autowired
    private CommonInfoBzImpl commonInfoBz;

    /**
     * @Author huchenying
     * @Description 通过字符串查询周围地点，返回地名和经纬度
     * @Date 2021/12/14 12:07
     **/
    @PostMapping("/findPosition")
    public ResponseData<Object> findPosition(@RequestBody @Validated FindLocationRequestDTO requestDTO) {
        logger.info("findPosition start param ->{}", ToStringBuilder.reflectionToString(requestDTO));
        ResponseData<Object> responseData = new ResponseData<>();
        String url = "https://restapi.amap.com/v3/assistant/inputtips?";
        StringBuilder sb = new StringBuilder(url);
        sb.append("key=").append(requestDTO.getKey());
        sb.append("&");
        sb.append("keywords=").append(requestDTO.getKeywords());
        if (StringUtils.isNotEmpty(requestDTO.getCity())) {
            sb.append("&");
            sb.append("city=").append(requestDTO.getCity());
        }
        if (StringUtils.isNotEmpty(requestDTO.getLocation())) {
            sb.append("&");
            sb.append("location=").append(requestDTO.getLocation());
        }
        Object forObject = restTemplate.getForObject(sb.toString(), Object.class);
        return responseData.success(forObject);
    }

    /**
     * @Author huchenying
     * @Description 获取省市区信息
     * @Date 2021/12/14 12:07
     **/
    @GetMapping("/getLocal")
    public ResponseData<Object> getLocal() {
        return new ResponseData<Object>().success("");
    }

    /**
     * @Author huchenying
     * @Description 通过轨迹id获取实际行驶路程和行驶时间
     * @Date 2021/12/31 13:57
     **/
    @PostMapping("/getTrackByTrid")
    public ResponseData<TrackInfoResponseDTO> getTrackByTrid(@Validated @RequestBody TrackInfoRequestDTO requestDTO) {
        logger.info("getTrackByTrid start param -> {}", ToStringBuilder.reflectionToString(requestDTO));
        ResponseData<TrackInfoResponseDTO> responseData = new ResponseData<>();
        String url = "https://tsapi.amap.com/v1/track/terminal/trsearch";
        Map<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("sid", requestDTO.getSid());
        map.put("tid", requestDTO.getTid());
        map.put("trid", requestDTO.getTrid());
        ResponseData<Object> res = myHttpUtils.sendGetRequest(url, map);
        logger.info("orgin res -> {}", ToStringBuilder.reflectionToString(res));
        if (res.getCode() == Code.Success) {
            try {
                Object data = res.getData();
                String s = JSONObject.toJSONString(data);
                JSONObject jsonObject = JSON.parseObject(s).getJSONObject("data");
                JSONArray tracks = jsonObject.getJSONArray("tracks");
                JSONObject jsonObject1 = tracks.getJSONObject(0);
                Integer distance = jsonObject1.getInteger("distance");
                Long time = jsonObject1.getLong("time");
                TrackInfoResponseDTO trackInfoResponseDTO = new TrackInfoResponseDTO();
                trackInfoResponseDTO.setDistance(distance);
                trackInfoResponseDTO.setTime(time);
                trackInfoResponseDTO.setTrid(requestDTO.getTrid());
                logger.info("查询track结果 -> {}", ToStringBuilder.reflectionToString(trackInfoResponseDTO));
                responseData.setData(trackInfoResponseDTO);
                responseData.setCode(Code.Success);
            } catch (Exception e) {
                logger.error("解析轨迹查询结果时发生异常", e);
                responseData.setCode(Code.Fail);
                responseData.setMsg("结果解析异常");
            }
        } else {
            responseData.setCode(Code.Fail);
            responseData.setMsg(res.getMsg());
        }
        return responseData;
    }

    /**
     * @Author huchenying
     * @Description  路径规划
     * @Date 2022/3/14 10:28
     **/
    @PostMapping("/direction")
    public ResponseData<Object>  direction(@Validated @RequestBody DirectionRequestDTO directionRequestDTO){
        logger.info("direction start param -> {}",ToStringBuilder.reflectionToString(directionRequestDTO));
        String url = "https://restapi.amap.com/v5/direction/driving";
        Map<String, Object> map = new HashMap<>();
        map.put("key", "5c940527e7a1a30ebf63600e3645adfc");
        map.put("origin", directionRequestDTO.getOrigin());
        map.put("destination", directionRequestDTO.getDestination());
        map.put("origin_type", 0);
        map.put("show_fields", "polyline");
        return myHttpUtils.sendGetRequest(url, map);
    }

    /**
     * @Author huchenying
     * @Description 通过坐标找到下单的Topic
     * @Date 2022/3/15 22:22
     **/
    @PostMapping("/getBelongTopic")
    public ResponseData<String> getBelongTopic(@Validated @RequestBody DirectionRequestDTO directionRequestDTO){
        logger.info("getBelongTopic start param -> {}",ToStringBuilder.reflectionToString(directionRequestDTO));
        ResponseData<String> responseData = new ResponseData<>();
        try {
            String url = "https://tsapi.amap.com/v1/track/geofence/status/location";
            Map<String, Object> map = new HashMap<>();
            map.put("key", "5c940527e7a1a30ebf63600e3645adfc");
            map.put("sid", sid);
            map.put("location", directionRequestDTO.getOrigin());
            ResponseData<Object> responseData1 = myHttpUtils.sendGetRequest(url, map);
            logger.info("围栏查询结果 -> {}",ToStringBuilder.reflectionToString(responseData1));
            Object data = responseData1.getData();
            JSONObject data1 = JSONObject.parseObject(JSON.toJSONString(data));
            JSONObject data2 = JSONObject.parseObject(JSON.toJSONString(data1.getJSONObject("data")));
            JSONArray results = data2.getJSONArray("results");
            String topic = "0";
            for (Object result : results) {
                JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(result));
                int in = jsonObject1.getIntValue("in");
                if(in == 1){
                    topic = jsonObject1.getString("gfid");
                    logger.info("找到归属区域topic = [{}]",topic);
                    break;
                }
            }
//          String topic =  commonInfoBz.getBelongTopic(directionRequestDTO);
            responseData.setData(topic);
            responseData.setCode(Code.Success);
            return responseData;
        } catch (Exception e) {
            logger.error("订单归属topic获取失败");
            responseData.setCode(Code.Success);
            responseData.setData("0");
            return responseData;
        }
    }

    /**
     * @Author huchenying
     * @Description 获取所有 Topic配置
     * @Date 2022/3/15 23:16
     **/
    @PostMapping("/getAllTopic")
    public ResponseData<List<GaoDeGfidsResponseDTO>> getAllTopic(){
        logger.info("getAllTopic start");
        ResponseData<List<GaoDeGfidsResponseDTO>> responseData = new ResponseData<>();
        try {
            List<GaoDeGfidsResponseDTO> res = new ArrayList<>();
            List<GaodeGfids> gfids = commonInfoBz.getGfids();
            for (GaodeGfids gfid : gfids) {
                GaoDeGfidsResponseDTO gaoDeGfidsResponseDTO = new GaoDeGfidsResponseDTO();
                BeanUtils.copyProperties(gfid,gaoDeGfidsResponseDTO);
                res.add(gaoDeGfidsResponseDTO);
            }
            responseData.setData(res);
            responseData.setCode(Code.Success);
            return responseData;
        } catch (Exception e) {
            responseData.setMsg("获取Topic配置错误！");
            responseData.setCode(Code.Fail);
            return responseData;
        }
    }
}
